package com.example.backendhjh.service;

import com.example.backendhjh.dto.CartItemDTO;
import com.example.backendhjh.dto.CartItemResponseDTO;
import com.example.backendhjh.entity.CartItem;
import com.example.backendhjh.entity.Product;
import com.example.backendhjh.exception.ApiException;
import com.example.backendhjh.mapper.CartItemMapper;
import com.example.backendhjh.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    private final CartItemMapper cartItemMapper;
    private final ProductMapper productMapper;

    @Autowired
    public CartService(CartItemMapper cartItemMapper, ProductMapper productMapper) {
        this.cartItemMapper = cartItemMapper;
        this.productMapper = productMapper;
    }

    // 添加商品到购物车
    @Transactional
    public CartItemResponseDTO addToCart(CartItemDTO cartItemDTO) {
        if (cartItemDTO.getUserId() == null) {
            throw new ApiException(HttpStatus.BAD_REQUEST, "用户ID不能为空");
        }
        if (cartItemDTO.getProductId() == null) {
            throw new ApiException(HttpStatus.BAD_REQUEST, "商品ID不能为空");
        }

        // 检查商品库存
        Product product = productMapper.findById(cartItemDTO.getProductId());
        if (product == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "商品不存在");
        }
        if (product.getStock() < cartItemDTO.getQuantity()) {
            throw new ApiException(HttpStatus.BAD_REQUEST, "商品库存不足");
        }

        // 检查是否已存在相同商品
        CartItem existingItem = cartItemMapper.findByUserAndProduct(cartItemDTO.getUserId(), cartItemDTO.getProductId());

        CartItem cartItem;
        if (existingItem != null) {
            existingItem.setQuantity(existingItem.getQuantity() + cartItemDTO.getQuantity());
            cartItemMapper.updateQuantity(existingItem);
            cartItem = existingItem;
        } else {
            cartItem = new CartItem();
            cartItem.setUserId(cartItemDTO.getUserId());
            cartItem.setProductId(cartItemDTO.getProductId());
            cartItem.setQuantity(cartItemDTO.getQuantity());
            cartItem.setCreatedAt(LocalDateTime.now());

            int result = cartItemMapper.insert(cartItem);
            if (result <= 0) {
                throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "添加购物车失败");
            }
        }

        return convertToResponseDTO(cartItem);
    }

    // 根据用户ID获取购物车
    public List<CartItemResponseDTO> getCartByUser(Long userId) {
        List<CartItem> cartItems = cartItemMapper.findByUserId(userId);
        return cartItems.stream()
                .map(this::convertToResponseDTO)
                .collect(Collectors.toList());
    }

    // 更新购物车项数量
    @Transactional
    public CartItemResponseDTO updateQuantity(Long id, Integer quantity) {
        CartItem cartItem = cartItemMapper.findById(id);
        if (cartItem == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "购物车项不存在");
        }

        // 检查商品库存
        Product product = productMapper.findById(cartItem.getProductId());
        if (product == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "商品不存在");
        }
        if (product.getStock() < quantity) {
            throw new ApiException(HttpStatus.BAD_REQUEST, "商品库存不足");
        }

        cartItem.setQuantity(quantity);
        int result = cartItemMapper.updateQuantity(cartItem);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "更新购物车失败");
        }

        return convertToResponseDTO(cartItem);
    }

    // 从购物车中移除商品
    @Transactional
    public void removeFromCart(Long id) {
        CartItem cartItem = cartItemMapper.findById(id);
        if (cartItem == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "购物车项不存在");
        }

        int result = cartItemMapper.delete(id);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "删除购物车项失败");
        }
    }

    // 清空用户购物车
    @Transactional
    public void clearCart(Long userId) {
        int result = cartItemMapper.clearCart(userId);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "清空购物车失败");
        }
    }

    // 将CartItem转换为响应DTO
    private CartItemResponseDTO convertToResponseDTO(CartItem cartItem) {
        Product product = productMapper.findById(cartItem.getProductId());
        if (product == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "关联商品不存在");
        }

        CartItemResponseDTO dto = new CartItemResponseDTO();
        dto.setId(cartItem.getId());
        dto.setUserId(cartItem.getUserId());
        dto.setProductId(cartItem.getProductId());
        dto.setProductName(product.getName());
        dto.setProductImage(product.getImageUrl());
        dto.setProductPrice(product.getPrice());
        dto.setQuantity(cartItem.getQuantity());
        dto.setSubtotal(product.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())));
        dto.setCreatedAt(cartItem.getCreatedAt());
        return dto;
    }
}
